// 后台服务工作者脚本

// 插件安装时的初始化
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('LinkHunter - 链接猎手插件已安装');
    
    // 设置默认配置
    chrome.storage.local.set({
      autoSync: false,
      syncInterval: 60, // 分钟
      lastSync: null,
      bookmarks: [],
      theme: 'light'
    });
  }
});

// 标签提取函数
function extractTags(title, url, folder) {
  const tags = new Set();
  
  // 从文件夹名提取标签
  if (folder && folder !== '根目录') {
    folder.split('/').forEach(part => {
      if (part.trim()) tags.add(part.trim());
    });
  }
  
  // 从URL域名提取标签
  try {
    const domain = new URL(url).hostname.replace('www.', '');
    const domainParts = domain.split('.');
    if (domainParts.length > 1) {
      tags.add(domainParts[0]);
    }
  } catch (e) {}
  
  // 从标题提取常见关键词
  const commonKeywords = ['github', 'docs', 'api', 'tutorial', 'guide', 'blog', 'news', 'tool', 'dev', 'design'];
  const titleLower = title.toLowerCase();
  commonKeywords.forEach(keyword => {
    if (titleLower.includes(keyword)) {
      tags.add(keyword);
    }
  });
  
  return Array.from(tags).slice(0, 5); // 限制标签数量
}

// 监听书签变化事件，实现实时同步
chrome.bookmarks.onCreated.addListener((id, bookmark) => {
  console.log('新增书签:', bookmark);
  updateBookmarkCache();
});

chrome.bookmarks.onRemoved.addListener((id, removeInfo) => {
  console.log('删除书签:', id);
  updateBookmarkCache();
});

chrome.bookmarks.onChanged.addListener((id, changeInfo) => {
  console.log('书签变更:', id, changeInfo);
  updateBookmarkCache();
});

chrome.bookmarks.onMoved.addListener((id, moveInfo) => {
  console.log('书签移动:', id, moveInfo);
  updateBookmarkCache();
});

// 更新书签缓存
async function updateBookmarkCache() {
  try {
    const bookmarkTree = await chrome.bookmarks.getTree();
    const allBookmarks = flattenBookmarks(bookmarkTree);
    
    await chrome.storage.local.set({
      bookmarks: allBookmarks,
      lastSync: new Date().toISOString()
    });
    
    console.log(`书签缓存已更新，共 ${allBookmarks.length} 个书签`);
  } catch (error) {
    console.error('更新书签缓存失败:', error);
  }
}

// 扁平化书签树结构
function flattenBookmarks(bookmarkTree, parentPath = '') {
  let result = [];
  
  for (const node of bookmarkTree) {
    if (node.children) {
      // 这是一个文件夹
      const currentPath = parentPath ? `${parentPath}/${node.title}` : node.title;
      result = result.concat(flattenBookmarks(node.children, currentPath));
    } else if (node.url) {
      // 这是一个书签
      const tags = extractTags(node.title, node.url, parentPath);
      result.push({
        id: node.id,
        title: node.title,
        url: node.url,
        folder: parentPath || '根目录',
        dateAdded: node.dateAdded,
        tags: tags
      });
    }
  }
  
  return result;
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.action) {
    case 'syncBookmarks':
      updateBookmarkCache().then(() => {
        sendResponse({ success: true });
      }).catch((error) => {
        sendResponse({ success: false, error: error.message });
      });
      return true; // 保持消息通道开放
      
    case 'getBookmarks':
      chrome.storage.local.get(['bookmarks', 'lastSync']).then((result) => {
        sendResponse({
          bookmarks: result.bookmarks || [],
          lastSync: result.lastSync
        });
      });
      return true;
      
    case 'searchBookmarks':
      chrome.storage.local.get('bookmarks').then((result) => {
        const bookmarks = result.bookmarks || [];
        const query = request.query.toLowerCase();
        const filtered = bookmarks.filter(bookmark => 
          bookmark.title.toLowerCase().includes(query) ||
          bookmark.url.toLowerCase().includes(query) ||
          bookmark.folder.toLowerCase().includes(query)
        );
        sendResponse({ bookmarks: filtered });
      });
      return true;
  }
});

// 定期同步功能（可选）
let syncInterval;

chrome.storage.local.get(['autoSync', 'syncInterval']).then((result) => {
  if (result.autoSync && result.syncInterval) {
    startAutoSync(result.syncInterval);
  }
});

function startAutoSync(intervalMinutes) {
  if (syncInterval) {
    clearInterval(syncInterval);
  }
  
  syncInterval = setInterval(() => {
    updateBookmarkCache();
  }, intervalMinutes * 60 * 1000);
}

function stopAutoSync() {
  if (syncInterval) {
    clearInterval(syncInterval);
    syncInterval = null;
  }
}

// 监听存储变化，更新自动同步设置
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (namespace === 'local') {
    if (changes.autoSync || changes.syncInterval) {
      chrome.storage.local.get(['autoSync', 'syncInterval']).then((result) => {
        if (result.autoSync && result.syncInterval) {
          startAutoSync(result.syncInterval);
        } else {
          stopAutoSync();
        }
      });
    }
  }
});

// 插件卸载时清理
chrome.runtime.onSuspend.addListener(() => {
  stopAutoSync();
});